#include <fstream>
#include <ctime>
#include <common/Tools.h>
#include "Configuration.h"
#include <cstdlib>
#include <cstring>

bool CConfiguration::Load(const char * file_name)
{
    if(!file_name)
        return false;
    conf_file_ = file_name;
    std::ifstream inf(file_name);
    if(!inf.is_open())
        return false;
    Clear();
    std::string line;
    while(!inf.eof()){
        std::getline(inf,line);
        line = line.substr(0,line.find_first_of("#"));
        if(line.empty())
            continue;
        std::string::size_type i = line.find_first_of("=");
        content_[Tools::Trim(line.substr(0,i))] = Tools::Trim(line.substr(i + 1));
    }
    return true;
}

std::string CConfiguration::GetString(std::string key,std::string strdefault) const
{
    container_type::const_iterator wh = content_.find(key);
    if(wh == content_.end())
        return strdefault;
    return wh->second;
}

int CConfiguration::GetInt(std::string key,int ndefault,int min,int max) const
{
    container_type::const_iterator wh = content_.find(key);
    int ret = ndefault;
    if(wh != content_.end()){
        ret = atoi(wh->second.c_str());
        switch(*wh->second.rbegin()){
            case 'k':case 'K':
                ret <<= 10;
                break;
            case 'm':case 'M':
                ret <<= 20;
                break;
            case 'g':case 'G':
                ret <<= 30;
                break;
            default:;
        }
    }
    return (ret < min ? min : (ret > max ? max : ret));
}

